﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Dx.Common
{
    public abstract class DesHelper
    {
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="txt">要加密的文本</param>
        /// <param name="key">DES加密秘钥</param>
        /// <param name="val">DES加密向量</param>
        public static string DESEncryption(string txt, string key = "dxcfg185", string val = "Dj185185")
        {
            try
            {
                byte[] bytIn = Encoding.Default.GetBytes(txt);
                DESCryptoServiceProvider mobjCryptoService = new DESCryptoServiceProvider
                {
                    Key = Encoding.Default.GetBytes(key),
                    IV = Encoding.Default.GetBytes(val)
                };
                using (ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor())
                {
                    return Convert.ToBase64String(encrypto.TransformFinalBlock(bytIn, 0, bytIn.Length));
                }
            }
            catch { }
            return string.Empty;
        }

        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="txt">要解密的文本</param>
        /// <param name="key">DES加密秘钥</param>
        /// <param name="val">DES加密向量</param>
        public static string DESDecrypt(string txt, string key = "dxcfg185", string val = "Dj185185")
        {
            try
            {
                using (DESCryptoServiceProvider desc = new DESCryptoServiceProvider())
                {
                    byte[] bStr = Convert.FromBase64String(txt);
                    desc.Key = Encoding.Default.GetBytes(key);
                    desc.IV = Encoding.Default.GetBytes(val);
                    return Encoding.Default.GetString(desc.CreateDecryptor().TransformFinalBlock(bStr, 0, bStr.Length));
                }
            }
            catch { }
            return string.Empty;
        }
    }
}
